<template>
  <div class="app-container">
    <!-- 搜索表单区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="businessId" style="margin-left: 30px">
        <el-input v-model="queryParams.businessId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="老人姓名" prop="elderlyName" style="white-space: nowrap">
        <el-input v-model="queryParams.elderlyName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="老人身份证号" prop="idCard" style="white-space: nowrap; margin-left: 25px">
        <el-input v-model="queryParams.idCard" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <div style="display: flex; flex-wrap: wrap; margin-left: 30px">
        <el-form-item label="请假开始时间" prop="leaveStartTime" style="white-space: nowrap">
          <el-date-picker clearable v-model="queryParams.leaveStartTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择请假开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>
    </el-form>
    <hr style="margin-top: -4px;">
    <div class="qingjia"><button @click="handleGoToLeaveApproval">发起请假申请</button></div>


    <!-- 状态筛选标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" style="margin-bottom: 10px">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="请假中" name="onLeave"></el-tab-pane>
      <el-tab-pane label="超时未归" name="overtime"></el-tab-pane>
      <el-tab-pane label="已返回" name="returned"></el-tab-pane>
    </el-tabs>

    <!-- 请假记录表格 -->
    <el-table v-loading="loading" :data="filteredLeaveList" @selection-change="handleSelectionChange" border stripe
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column label="序号" align="center" width="80"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <!-- <el-table-column label="单据编号" align="center" prop="businessId" width="140" /> -->
      <el-table-column label="老人姓名" align="center" width="150">
        <template #default="scope">
          {{ scope.row.elderlyName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="老人身份证号" align="center" width="200">
        <template #default="scope">
          {{ scope.row.idCard || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="请假开始时间" align="center" prop="leaveStartTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.leaveStartTime, "{y}-{m}-{d} {h}:{i}:{s}") ||
            "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预请假结束时间" align="center" prop="expectedEndTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.expectedEndTime, "{y}-{m}-{d} {h}:{i}:{s}") ||
            "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.actualEndTime, "{y}-{m}-{d} {h}:{i}:{s}") || "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="200">
        <template #default="scope">
          {{ scope.row.creatorName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") || "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假状态" align="center" width="120">
  <template #default="scope">
    <!-- 根据pizhun字段值匹配标签颜色和显示文本 -->
    <el-tag 
      :type="scope.row.pizhun === '已返回' ? 'success' : (scope.row.pizhun === '请假中' ? 'warning' : 'danger')"
    >
      {{ scope.row.pizhun || "未设置" }}
    </el-tag>
  </template>
</el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" :disabled="!!scope.row.actualEndTime"
            v-hasPermi="['leave:leavemanage:edit']" style="margin-right: 8px">
            返回
          </el-button>
          <el-button link type="primary" @click="handleView(scope.row)" v-hasPermi="['system:contract:view']">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" style="margin-top: 16px; text-align: right" />

    <!-- 填写返回时间弹窗 -->
    <el-dialog :title="returnDialogTitle" v-model="openReturnDialog" width="400px" append-to-body
      :close-on-click-modal="false">
      <el-form ref="returnFormRef" :model="returnForm" :rules="returnRules" label-width="120px" size="medium">
        <el-form-item label="实际返回时间" prop="actualEndTime">
          <el-date-picker v-model="returnForm.actualEndTime" type="datetime" placeholder="请选择实际返回时间"
            value-format="YYYY-MM-DD HH:mm:ss" default-time="12:00:00" :disabled-date="(date) => date > new Date()"
            required />
        </el-form-item>
        <!-- 输入框：实际请假天数（自动计算，禁止手动编辑） -->
        <el-form-item label="实际请假天数" prop="actualLeaveDays">
          <el-input-number v-model="returnForm.actualLeaveDays" min="0" max="100" step="1" placeholder="自动计算"
            required :disabled="true" />
        </el-form-item>
        <el-form-item label="返回备注" prop="actualReturnRemark">
          <el-input v-model="returnForm.actualReturnRemark" type="textarea" placeholder="请输入返回备注（可选）" maxlength="200"
            show-word-limit rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openReturnDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitReturn">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Leavemanage">
// 引入接口
import {
  listLeavemanage,
  delLeavemanage,
  updateLeavemanage,
} from "@/api/leave/leavemanage";
// 引入Vue核心API
import {
  ref,
  reactive,
  toRefs,
  onMounted,
  getCurrentInstance,
  computed,
  watch,
} from "vue";
// 引入Element Plus组件
import { ElMessage } from "element-plus";
// 引入路由
import { useRouter } from "vue-router";
// 引入分页组件
import Pagination from "@/components/Pagination/index.vue";

import useUserStore from "@/store/modules/user";
// 2. 获取用户存储实例
const userStore = useUserStore();
// 3. 在脚本中打印用户信息
console.log("当前登录用户信息：", {
  id: userStore.id,
  name: userStore.name,
  nickName: userStore.nickName,
  avatar: userStore.avatar,
  roles: userStore.roles,
  permissions: userStore.permissions,
});


// 初始化路由实例
const router = useRouter();
// 获取当前组件实例
const { proxy } = getCurrentInstance();

const handleGoToLeaveApproval = () => {
  // 跳转到目标路由
  router.push("/togetherwork/togetherwork1/leaveappeoval");
};

// 时间格式化函数
function parseTime(time, format = "{y}-{m}-{d} {h}:{i}:{s}") {
  if (!time || typeof time !== "string") return "";
  const date = new Date(time);
  if (isNaN(date.getTime())) return ""; // 处理无效时间
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
  };
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    return value.toString().padStart(2, "0");
  });
}

// 返回时间弹窗相关配置
const returnDialogTitle = ref("填写返回时间");
const openReturnDialog = ref(false);
const currentRow = ref({});
const returnForm = reactive({
  actualEndTime: new Date().toISOString().slice(0, 19).replace("T", " "),
  actualLeaveDays: 0, // 初始化实际请假天数为0
  actualReturnRemark: "",
});
const returnRules = reactive({
  actualEndTime: [
    { required: true, message: "请选择实际返回时间", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (currentRow.value.leaveStartTime) {
          const leaveStart = new Date(currentRow.value.leaveStartTime);
          const actualEnd = new Date(value);
          if (actualEnd < leaveStart) {
            callback(new Error("实际返回时间不能早于请假开始时间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  actualLeaveDays: [
    { required: true, message: "实际请假天数不能为空", trigger: "blur" },
    { type: "number", min: 0, message: "实际请假天数不能小于0", trigger: "blur" }
  ],
  actualReturnRemark: [
    { max: 200, message: "备注不能超过200个字符", trigger: "blur" },
  ],
});
const returnFormRef = ref(null);

// ---------- 新增：监听实际返回时间变化，自动计算请假天数 ----------
watch(
  () => returnForm.actualEndTime,
  (newActualEndTime) => {
    // 确保有请假开始时间和实际返回时间
    if (currentRow.value.leaveStartTime && newActualEndTime) {
      const leaveStart = new Date(currentRow.value.leaveStartTime);
      const actualEnd = new Date(newActualEndTime);
      
      // 计算时间差（毫秒），转换为天数（1天 = 86400000毫秒）
      const timeDiff = actualEnd - leaveStart;
      const days = Math.ceil(timeDiff / (24 * 60 * 60 * 1000));
      
      // 赋值给实际请假天数（确保不小于0）
      returnForm.actualLeaveDays = Math.max(days, 0);
    }
  },
  { immediate: true } // 初始加载时也计算一次
);

// 表格与筛选相关数据
const activeTab = ref("all");
const leavemanageList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 根据activeTab计算过滤后的列表
const filteredLeaveList = computed(() => {
  // if (activeTab.value === "all") {
  //   return leavemanageList.value;
  // } else if (activeTab.value === "onLeave") {
  //   return leavemanageList.value.filter((item) => {
  //     return (
  //       !item.actualEndTime && new Date() <= new Date(item.expectedEndTime)
  //     );
  //   });
  // } else if (activeTab.value === "overtime") {
  //   return leavemanageList.value.filter((item) => {
  //     return !item.actualEndTime && new Date() > new Date(item.expectedEndTime);
  //   });
  // } else if (activeTab.value === "returned") {
  //   return leavemanageList.value.filter((item) => item.actualEndTime);
  // }
  // return leavemanageList.value;
  switch (activeTab.value) {
    case "all":
      return leavemanageList.value; // 全部：显示所有leave_status != '待审核'的记录
    case "onLeave":
      // 筛选pizhun为“请假中”的记录
      return leavemanageList.value.filter(item => item.pizhun === "请假中");
    case "overtime":
      // 筛选pizhun为“超时未归”的记录
      return leavemanageList.value.filter(item => item.pizhun === "超时未归");
    case "returned":
      // 筛选pizhun为“已返回”的记录
      return leavemanageList.value.filter(item => item.pizhun === "已返回");
    default:
      return leavemanageList.value;
  }
});

// 查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: null,
    elderlyName: null,
    idCard: null,
    leaveStartTime: null,
    leaveStatus: 2,
  },
  rules: {},
});

const { queryParams } = toRefs(data);

// 标签切换事件
function handleTabClick(tab) {
  activeTab.value = tab.name;
}

// 查询列表数据
function getList() {
  loading.value = true;
  listLeavemanage(queryParams.value)
    .then(async (response) => {
      const leaveList = response.rows || [];
      // 筛选未返回且需要更新状态的记录（pizhun为“请假中”但已超期）
      const updateTasks = leaveList
        .filter(item => !item.actualEndTime && item.pizhun === "请假中")
        .map(item => {
          const now = new Date();
          const expectedEnd = new Date(item.expectedEndTime);
          // 超期则更新为“超时未归”
          if (now > expectedEnd) {
            return updateLeavemanage({ id: item.id, pizhun: "超时未归" });
          }
          return Promise.resolve();
        });

      // 批量更新状态后，重新拉取最新列表
      await Promise.all(updateTasks);
      return listLeavemanage(queryParams.value);
    })
    .then((response) => {
      leavemanageList.value = response.rows || [];
      total.value = response.total || 0;
    })
    .catch(() => {
      leavemanageList.value = [];
      total.value = 0;
      ElMessage.error("获取请假列表失败，请重试");
    })
    .finally(() => {
      loading.value = false;
    });
}

// 初始化列表
onMounted(() => {
  getList();
  if (proxy?.useDict) {
    proxy.useDict("people", "sys_user_sex");
  }
});

// 搜索操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置搜索
function resetQuery() {
  if (proxy?.resetForm && queryRef.value) {
    proxy.resetForm(queryRef.value);
  }
  queryParams.value.leaveStartTime = null;
  handleQuery();
}

// 选择项变化
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id) || [];
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
}

// 打开返回时间弹窗
function handleUpdate(row) {
  if (row.actualEndTime) {
    ElMessage.warning("该记录已返回，无需重复操作");
    return;
  }
  currentRow.value = { ...row };
  // 初始化默认时间（不早于请假开始时间）
  const defaultTime = new Date() > new Date(row.leaveStartTime)
    ? new Date().toISOString().slice(0, 19).replace("T", " ")
    : row.leaveStartTime;
  returnForm.actualEndTime = defaultTime;
  returnForm.actualReturnRemark = "";
  // 初始化时触发一次计算（避免默认时间无天数）
  if (defaultTime) {
    const leaveStart = new Date(row.leaveStartTime);
    const actualEnd = new Date(defaultTime);
    const timeDiff = actualEnd - leaveStart;
    returnForm.actualLeaveDays = Math.max(Math.ceil(timeDiff / (24 * 60 * 60 * 1000)), 0);
  }
  if (returnFormRef.value) {
    returnFormRef.value.clearValidate();
  }
  openReturnDialog.value = true;
}

// 提交返回时间
function submitReturn() {
  if (!returnFormRef.value) return;

  returnFormRef.value.validate((valid) => {
    if (valid) {
      const updateParams = {
        id: currentRow.value.id,
        actualEndTime: returnForm.actualEndTime,
        actualLeaveDays: returnForm.actualLeaveDays, // 新增：提交自动计算的天数
        actualReturnRemark: returnForm.actualReturnRemark,
        pizhun: "已返回", // 状态更新为已返回
        returnOperator: userStore.userName, // 记录销假人（假设从全局获取用户名）
        returnTime: new Date().toISOString().slice(0, 19).replace("T", " ") // 记录销假时间
      };

      updateLeavemanage(updateParams)
        .then(() => {
          ElMessage.success("返回时间填写成功，状态已更新");
          openReturnDialog.value = false;
          getList();
        })
        .catch(() => {
          ElMessage.error("填写失败，请重试");
        });
    }
  });
}

// 删除操作
function handleDelete(row) {
  const _ids = row ? [row.id] : ids.value;
  if (_ids.length === 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  }

  proxy.$modal
    .confirm(`是否确认删除请假编号为"${_ids.join(",")}"的数据项？`)
    .then(() => {
      return delLeavemanage(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

// 导出操作
function handleExport() {
  proxy.download(
    "leave/leavemanage/export",
    { ...queryParams.value },
    `leavemanage_${new Date().getTime()}.xlsx`
  );
}

// 查看详情
function handleView(row) {
  router.push({
    path: "/leave/leavemanage/LeaveView",
    query: { leaveId: row.id },
  });
}


// 表单ref定义
const queryRef = ref(null);
// 状态映射：数据库pizhun字段值 → 前端显示文本
// const statusMap = {
//   onLeave: "请假中",
//   overtime: "超时未归",
//   returned: "已返回"
// };
</script>

<style scoped>
.qingjia{
  width: 100%;
  text-align: right;
  padding: 14px 0;
}
.qingjia button{
  width: 140px;
  height: 32px;
  border-radius: 4px;
  background-color: #409eff;
  color: #fff;
  border: none;
  font-size: 14px;
  transition: background-color 0.5s ease;
}
.qingjia button:hover{
  background-color: #0168d6;
}</style>